package com.sky.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "sky.qiniu")
public class QiniuOssUtil {
   // private String endpoint; // 这个字段可能不再需要用于生成URL
    private String accessKey;
    private String secretKey;
    private String bucketName;
    private String bindDomain; // 新增字段，用于存储绑定域名

    private UploadManager uploadManager;
    private Auth auth;

    @PostConstruct
    public void init() {
        log.info("七牛云配置初始化...");
        log.info("Bucket: {}", bucketName);
        log.info("Bind Domain: {}", bindDomain); // 记录绑定域名

        Configuration cfg = new Configuration(Region.autoRegion());
        this.uploadManager = new UploadManager(cfg);
        this.auth = Auth.create(accessKey.trim(), secretKey.trim());
    }

    public String upload(byte[] bytes, String objectName) {
        try {
            String upToken = auth.uploadToken(bucketName);
            Response response = uploadManager.put(bytes, objectName, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            // 使用绑定域名构建访问URL
            String imageUrl = String.format("http://%s/%s", bindDomain, putRet.key);
            log.info("图片上传成功，访问URL为: {}", imageUrl);
            return imageUrl;
        } catch (QiniuException ex) {
            log.error("七牛云上传失败 => 错误码：{}", ex.code());
            log.error("错误详情：{}", ex.response.toString());
            throw new RuntimeException("文件上传失败: " + ex.getMessage());
        } catch (Exception ex) {
            log.error("上传出现未知异常", ex);
            throw new RuntimeException("文件上传服务异常");
        }
    }
}